package com.tzbank.poc.controller;

import com.alibaba.fastjson.JSONObject;
import com.tzbank.poc.common.CommonConstant;
import com.tzbank.poc.common.CommonError;
import com.tzbank.poc.exception.ServiceException;
import com.tzbank.poc.model.AccountBalance;
import com.tzbank.poc.model.BindBankCard;
import com.tzbank.poc.model.BindBankCardKey;
import com.tzbank.poc.model.Customer;
import com.tzbank.poc.service.CustomerService;
import com.tzbank.poc.util.IdUtil;
import com.tzbank.poc.util.ReturnMapUtil;
import com.tzbank.poc.util.ValidateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: li_zheng2
 * @Date: 2019/1/21
 */
@Controller
@RequestMapping(value = "/user")
public class CustomerController {
    @Autowired
    private CustomerService customerService;


    private Logger logger = LoggerFactory.getLogger(CustomerController.class);

    @ResponseBody
    @RequestMapping(value = "/registAndOpenAccount", produces = {"application/json;charset=UTF-8"})
    public Map<String, Object> registAndOpenAccount(@RequestBody Map map) throws SQLException {

        String userNo;
        Customer customer = new Customer();
        Map<String, String> bodyMap = ReturnMapUtil.getBody(map);
        if (StringUtils.isEmpty(bodyMap.get("phoneNo"))) {
            logger.error("phoneNo is Empty");
            throw new ServiceException(CommonError.PARAM_EMPTY, "phoneNo is Empty");
        } else {
            customer.setPhoneNo(bodyMap.get("phoneNo").toString());
        }

        if (StringUtils.isEmpty(bodyMap.get("userPassword"))) {
            logger.error("userPassword is Empty");
            return ReturnMapUtil.returnFail("userPassword is Empty");
        } else {
            customer.setPassword(bodyMap.get("userPassword").toString());
        }
        String flag = bodyMap.get("flag");
        Map<String, Object> resultMap = customerService.queryCustomerByPhoneNo(customer.getPhoneNo());

        //登录
        if (CommonConstant.LOGON.equals(flag)) {
            /*-----判断手机号------*/
            if (StringUtils.isEmpty(resultMap)) {
                logger.error("phoneNo is not exist");
                return ReturnMapUtil.returnFail("phoneNo is not exist");
            }
            /*------判断密码-------*/
            if (customer.getPassword().equals(resultMap.get("password"))) {
                Map m = new HashMap();
                m.put("userNo", resultMap.get("userNo"));
                ReturnMapUtil.setBodyMap(m);
                return ReturnMapUtil.getSuccessMap();
            } else {
                logger.error("password is error");
                return ReturnMapUtil.returnFail("password is error");
            }
        }
        //注册
        if (CommonConstant.REGIST.equals(flag)) {
            if (!StringUtils.isEmpty(resultMap)) {
                logger.error("phoneNo is already exist");
                return ReturnMapUtil.returnFail("phoneNo is already exist");
            }
        }
        userNo = IdUtil.generatorId();
        customer.setUserNo(userNo);
        int Num = customerService.addCustomer(customer);
        if (Num != 1) {
            ReturnMapUtil.setHeaderMap();
            ReturnMapUtil.getHeaderMap().put("RetCode", "0001");
            ReturnMapUtil.getHeaderMap().put("RetStatus","F");
            ReturnMapUtil.getHeaderMap().put("RetMsg", "登记表失败");
            return ReturnMapUtil.getFailureMap();
        }

        Map ma = new HashMap<>();
        ma.put("userNo",userNo);
        ReturnMapUtil.setBodyMap(ma);

        Map returnMap = ReturnMapUtil.getSuccessMap();

        return returnMap;
    }

    @ResponseBody
    @RequestMapping(value = "/insertOrUpdateUserInfo", produces = {"application/json;charset=UTF-8"})
    public Map<String, Object> insertOrUpdateUserInfo(@RequestBody Map map) throws Exception {

        Map<String, String> bodyMap = ReturnMapUtil.getBody(map);
       Customer customer = JSONObject.parseObject(JSONObject.toJSONString(bodyMap),Customer.class);
//        String userNo = bodyMap.get("userNo").toString();
//        Customer customer = new Customer();
//        customer.setUserno(userNo);
//        customer.setPhoneno(bodyMap.get("phoneNo"));
//        customer.setAge(Integer.parseInt(bodyMap.get("age")));
//        customer.setAnnualincome(bodyMap.get("annualIncome"));
//        customer.setCertificatetype(bodyMap.get("certificateType"));
//        customer.setCertificateno(bodyMap.get("certificateNo"));
//        customer.setCountrycode(bodyMap.get("countryCode"));
//        customer.setSextype(bodyMap.get("sexType"));
//        customer.setWorklife(Integer.parseInt(bodyMap.get("workLife")));
//        customer.setEducationlevel(bodyMap.get("educationLevel"));
//        customer.setFamilyannualincome(bodyMap.get("familyAnnualIncome"));
//        customer.setFamilyassets(bodyMap.get("familyAssets"));
//        customer.setFamilydebt(bodyMap.get("familyDebt"));
//        customer.setPaymenttype(bodyMap.get("paymentType"));
//        customer.setPaymentauthentication(bodyMap.get("paymentAuthentication"));
//        customer.setPaylimitation(BigDecimal.valueOf(Long.parseLong(bodyMap.get("payLimitation"))));
//        customer.setPaymentpassword(bodyMap.get("paymentPassword"));
//        customer.setIsrealname(bodyMap.get("isRealName"));
        customerService.updateCustomer(customer);

        return ReturnMapUtil.getSuccessNoBody();
    }

    @ResponseBody
    @RequestMapping(value = "/checkRealName", produces = {"application/json;charset=UTF-8"})
    public Map<String, Object> checkRealName(@RequestBody Map map) throws Exception {
        Map<String, String> bodyMap = ReturnMapUtil.getBody(map);
        String userNo = bodyMap.get("userNo").toString();
        Customer customer = new Customer();
        customer.setIsRealName("Y");
        customer.setUserNo(userNo);
        customerService.updateCustomer(customer);
        Map body = new HashMap();
        body.put("isRealName", "Y");
        ReturnMapUtil.setBodyMap(body);
        return ReturnMapUtil.getSuccessMap();
    }

    @ResponseBody
    @RequestMapping(value = "/identityVerification", produces = {"application/json;charset=UTF-8"})
    public Map<String, Object> identityVerification(@RequestBody Map map) throws Exception {
        Map returnMap = ReturnMapUtil.getSuccessNoBody();
        return returnMap;
    }

    @ResponseBody
    @RequestMapping(value = "/queryUserInfo", produces = {"application/json;charset=UTF-8"})
    public Map<String,Object> queryUserInfo(@RequestBody Map map) throws Exception{
        Map bodyMap = ReturnMapUtil.getBody(map);
        String userNo = bodyMap.get("userNo").toString();
        Map map1 = customerService.queryCustomerInfo(userNo);
        ReturnMapUtil.setBodyMap(map1);
        return ReturnMapUtil.getSuccessMap();

    }

    @ResponseBody
    @RequestMapping(value = "/openAccountBindCard", produces = {"application/json;charset=UTF-8"})
    public Map<String,Object> openAccountBindCard(@RequestBody Map map) throws Exception{
        Map bodyMap = ReturnMapUtil.getBody(map);
        String userNo = bodyMap.get("userNo").toString();
        String creditCard = bodyMap.get("creditCard").toString();

        BindBankCard bindBankCard = new BindBankCard();
        bindBankCard.setCardNo(creditCard);
        bindBankCard.setUserNo(userNo);

        Map returnMap = customerService.openAccountBindCard(bindBankCard);

        return returnMap;
    }

    @ResponseBody
    @RequestMapping(value = "/queryBindCardList", produces = {"application/json;charset=UTF-8"})
    public Map<String,Object> queryBindCardList(@RequestBody Map map) throws Exception{
        Map bodyMap = ReturnMapUtil.getBody(map);
        String userNo = bodyMap.get("userNo").toString();

        List<BindBankCard> cardList = customerService.queryBindCardList(userNo);
        Map<String,Object> listMap = new HashMap<>();
        listMap.put("creditCardList",cardList);
        ReturnMapUtil.setBodyMap(listMap);
        return ReturnMapUtil.getSuccessMap();
    }

    @ResponseBody
    @RequestMapping(value ="/deleteBindCard", produces = {"application/json;charset=UTF-8"})
    public Map<String,Object> deleteBindCard(@RequestBody Map map) throws Exception{
        Map bodyMap = ReturnMapUtil.getBody(map);
        String userNo = bodyMap.get("userNo").toString();
        String creditCard = bodyMap.get("creditCard").toString();

        BindBankCardKey bindBankCardKey = new BindBankCardKey();
        bindBankCardKey.setCardNo(creditCard);
        bindBankCardKey.setUserNo(userNo);

        customerService.deleteBindCard(bindBankCardKey);
        return ReturnMapUtil.getSuccessNoBody();
    }

    @ResponseBody
    @RequestMapping(value="/changeBindingPhoneNo", produces = {"application/json;charset=UTF-8"})
    public Map<String,Object> changeBindingPhoneNo(@RequestBody Map map) throws Exception{
        Map bodyMap = ReturnMapUtil.getBody(map);
        String userNo = bodyMap.get("userNo").toString();
        String phoneNo = bodyMap.get("phoneNo").toString();
        Customer customer = new Customer();
        customer.setUserNo(userNo);
        customer.setPhoneNo(phoneNo);
        customerService.updateCustomer(customer);
        return ReturnMapUtil.getSuccessNoBody();
    }


}
